#!/bin/bash

# 颜色定义
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

# 检查是否为 root 用户
if [ "$(id -u)" -eq 0 ]; then
    echo -e "${RED}错误：请不要使用 root 用户运行此脚本！${NC}"
    echo -e "${YELLOW}请用普通用户运行，脚本会自动请求 sudo 权限。${NC}"
    exit 1
fi

# 检查是否为 Ubuntu 系统
if ! grep -q "Ubuntu" /etc/os-release; then
    echo -e "${RED}错误：此脚本仅适用于 Ubuntu 系统！${NC}"
    exit 1
fi

# 安装 Docker
install_docker() {
    echo -e "${GREEN}正在安装 Docker...${NC}"
    sudo apt-get update -qq
    sudo apt-get install -y -qq \
        apt-transport-https \
        ca-certificates \
        curl \
        software-properties-common \
        gnupg \
        lsb-release \
        jq

    # 添加 Docker 官方 GPG 密钥
    curl -fsSL --retry 5 https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

    # 添加 Docker 仓库
    echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

    # 安装 Docker
    sudo apt-get update -qq
    sudo apt-get install -y -qq docker-ce docker-ce-cli containerd.io

    # 启动 Docker 并设置开机自启
    sudo systemctl start docker
    sudo systemctl enable docker

    echo -e "${GREEN}Docker 安装完成！${NC}"
}

# 安装 Docker Compose
install_docker_compose() {
    echo -e "${GREEN}正在安装 Docker Compose...${NC}"
    COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r .tag_name)
    sudo curl -L "https://github.com/docker/compose/releases/download/$COMPOSE_VERSION/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    sudo chmod +x /usr/local/bin/docker-compose

    echo -e "${GREEN}Docker Compose 安装完成！${NC}"
}

# 主安装流程
echo -e "\n${GREEN}开始 Docker 安装流程...${NC}"

# 检查 Docker
if ! command -v docker &> /dev/null; then
    install_docker
else
    echo -e "${YELLOW}Docker 已安装，跳过安装步骤。${NC}"
fi

# 检查 Docker Compose
if ! command -v docker-compose &> /dev/null; then
    install_docker_compose
else
    echo -e "${YELLOW}Docker Compose 已安装，跳过安装步骤。${NC}"
fi

# 将用户加入 docker 组（如果尚未加入）
if ! groups $USER | grep -q '\bdocker\b'; then
    echo -e "${GREEN}将当前用户加入 docker 组...${NC}"
    sudo usermod -aG docker $USER
    
    # 关键步骤：立即应用组权限
    echo -e "${YELLOW}正在应用权限变更（无需重启）...${NC}"
    exec sg docker newgrp $(id -gn)
else
    echo -e "${YELLOW}用户已在 docker 组中${NC}"
fi

# 验证安装
echo -e "\n${GREEN}验证安装...${NC}"
docker --version
docker-compose --version

# 测试 Docker 是否可用
if docker run --rm hello-world &> /dev/null; then
    echo -e "${GREEN}Docker 测试成功！${NC}"
else
    echo -e "${RED}Docker 测试失败！请尝试以下命令：${NC}"
    echo -e "1. 手动应用组权限：${YELLOW}newgrp docker${NC}"
    echo -e "2. 或者完全重启终端会话"
fi